package com.auto.survey.widget.dialog.radiodialog

import android.app.AlertDialog
import android.content.Context
import android.view.Gravity
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup

class RadioDialogHelper private constructor(
    private val context: Context,
    private val title: String,
    private val items: List<RadioBean>,
    private val selectedIndex: Int,
    private val onItemSelected: (Int, RadioBean) -> Unit
) {

    fun show() {
        val radioGroup = RadioGroup(context).apply {
            orientation = RadioGroup.VERTICAL
            items.forEachIndexed { index, item ->

                val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)
                layoutParams.setMargins(10, 30, 10,10)
                layoutParams.gravity = Gravity.CENTER_VERTICAL
                val radioButton = RadioButton(context)
                radioButton.setPadding(10, 10, 10 ,10)
                radioButton.layoutParams  = layoutParams
                radioButton.textSize = 16f

                addView(radioButton.apply {
                    id = index
                    text = item.content
                    isChecked = index == selectedIndex
                })
            }
        }

        AlertDialog.Builder(context)
            .setTitle(title)
            .setView(radioGroup)
            .setPositiveButton("确定") { dialog, _ ->
                val selectedId = radioGroup.checkedRadioButtonId
                if (selectedId != -1) {
                    onItemSelected(selectedId, items[selectedId])
                }
                dialog.dismiss()
            }
            .setNegativeButton("取消", null)
            .create()
            .show()
    }

    class Builder(private val context: Context) {
        private var title: String = ""
        private var items: List<RadioBean> = emptyList()
        private var selectedIndex: Int = 0
        private var onItemSelected: (Int, RadioBean) -> Unit = { _, _ -> }

        fun setTitle(title: String) = apply { this.title = title }
        fun setItems(items: List<RadioBean>) = apply { this.items = items }
        fun setSelectedIndex(index: Int) = apply { this.selectedIndex = index }
        fun setOnItemSelectedListener(listener: (Int, RadioBean) -> Unit) = apply { this.onItemSelected = listener }

        fun build() = RadioDialogHelper(context, title, items, selectedIndex, onItemSelected)
    }

    data class RadioBean(var key:Int, var content:String)
}